<?php

namespace App\Services;

use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;

/**
 * 用户服务类
 * 
 * 职责：
 * - 处理用户相关的业务逻辑
 * - 用户创建、更新、删除
 * - 用户权限管理
 * - 用户统计数据
 */
class UserService extends BaseService
{
    /**
     * 获取用户列表
     * 
     * @param array $filters 过滤条件
     * @param int $perPage 每页数量
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getUsers(array $filters = [], int $perPage = 10): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        $query = User::withCount(['posts', 'comments']);

        // 搜索过滤
        if (!empty($filters['search'])) {
            $search = $filters['search'];
            $query->where(function ($q) use ($search) {
                $q->where('name', 'like', "%{$search}%")
                  ->orWhere('email', 'like', "%{$search}%");
            });
        }

        // 排序处理
        if (!empty($filters['sort'])) {
            [$sortField, $sortDirection] = explode(',', $filters['sort']);
            $sortDirection = in_array($sortDirection, ['asc', 'desc']) ? $sortDirection : 'desc';
        } else {
            $sortField = 'created_at';
            $sortDirection = 'desc';
        }
        
        switch ($sortField) {
            case 'posts_count':
            case 'comments_count':
                $query->orderBy($sortField, $sortDirection);
                break;
            case 'name':
            case 'email':
            case 'created_at':
                $query->orderBy($sortField, $sortDirection);
                break;
            default:
                $query->orderBy('created_at', 'desc');
                break;
        }

        return $query->paginate($perPage)->withQueryString();
    }

    /**
     * 创建用户
     * 
     * @param array $data 用户数据
     * @return User
     */
    public function create(array $data): User
    {
        return DB::transaction(function () use ($data) {
            $user = User::create([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => Hash::make($data['password']),
            ]);

            // 注意：当前项目没有角色系统，如需添加角色功能，请先创建 roles 表和关系

            return $user->fresh();
        });
    }

    /**
     * 更新用户
     * 
     * @param User $user 用户模型
     * @param array $data 用户数据
     * @return User
     */
    public function update(User $user, array $data): User
    {
        return DB::transaction(function () use ($user, $data) {
            $updateData = [
                'name' => $data['name'],
                'email' => $data['email'],
            ];

            // 如果提供了新密码，则更新
            if (!empty($data['password'])) {
                $updateData['password'] = Hash::make($data['password']);
            }

            $user->update($updateData);

            // 注意：当前项目没有角色系统，如需添加角色功能，请先创建 roles 表和关系

            return $user->fresh();
        });
    }

    /**
     * 删除用户
     * 
     * @param User $user 用户模型
     * @return bool
     */
    public function delete(User $user): bool
    {
        return DB::transaction(function () use ($user) {
            // 删除用户
            return $user->delete();
        });
    }

    /**
     * 获取用户详情
     * 
     * @param User $user 用户模型
     * @return array
     */
    public function getUserDetail(User $user): array
    {
        $user->load(['posts', 'comments']);

        return [
            'id' => $user->id,
            'name' => $user->name,
            'email' => $user->email,
            'email_verified_at' => $user->email_verified_at,
            'created_at' => $user->created_at,
            'updated_at' => $user->updated_at,
            'posts_count' => $user->posts_count ?? $user->posts()->count(),
            'comments_count' => $user->comments_count ?? $user->comments()->count(),
        ];
    }

    /**
     * 获取用户统计数据
     * 
     * @return array
     */
    public function getStats(): array
    {
        return [
            'total' => User::count(),
            'verified' => User::whereNotNull('email_verified_at')->count(),
            'unverified' => User::whereNull('email_verified_at')->count(),
            'with_posts' => User::has('posts')->count(),
            'with_comments' => User::has('comments')->count(),
        ];
    }
}

